package com.caigou.modules.famous.ui.subscribe.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.famous.R
import com.caigou.modules.famous.adpter.FamousItemAdapter
import com.caigou.modules.famous.bean.FamousItemBean
import com.caigou.modules.famous.databinding.FragmentSubscribeRecordBinding
import com.caigou.modules.famous.ui.subscribe.FamousMySubscribeActivity
import com.caigou.modules.famous.viewmodel.SubscribeViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/09
 */
@AndroidEntryPoint
class SubscribeRecordFragment : BaseFragment() {

    private var _binding: FragmentSubscribeRecordBinding? = null
    private val binding get() = _binding!!

    private val subscribeViewModel: SubscribeViewModel by viewModels()

    private var dareTypeId = 11
    private var clickPos = -1

    private val mAdapter: FamousItemAdapter by lazy {
        FamousItemAdapter(mutableListOf())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentSubscribeRecordBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.subscribeRecordSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchSubscribeRecordList()
            }
        }

        binding.subscribeRecordRecyclerView.run {
            layoutManager = LinearLayoutManager(requireActivity())
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val type = (requireActivity() as FamousMySubscribeActivity).famousType
            val userId = mAdapter.getItem(position).userId
            ARouter.getInstance().build(RouterPath.Famous.PAGE_PERSONAL)
                .withInt(AppConstants.FAMOUS_TYPE, type)
                .withString(AppConstants.USER_ID, userId)
                .navigation()
        }

        mAdapter.setOnItemChildClickListener { _, view, position ->
            clickPos = position
            when (view.id) {
                R.id.item_famous_ll_like -> {
                    val item = mAdapter.data[position]
                    val famousTyoe = (requireActivity() as FamousMySubscribeActivity).famousType
                    if (item.like) {
                        return@setOnItemChildClickListener
                    }
                    subscribeViewModel.setLike(item.dareContentId, famousTyoe, AppBackgroundInfo.instance.userBean!!.userId, item.userId)

                }
                R.id.item_famous_ll_subscribe -> {
                    val item = mAdapter.data[position]
                    val famousType = (requireActivity() as FamousMySubscribeActivity).famousType
                    subscribeViewModel.setSubscribe(dareTypeId, famousType, AppBackgroundInfo.instance.userBean!!.userId, item.userId)
                }
            }
        }

        binding.subscribeRecordLayoutSelector.challengeTypeSelectorRgSelector.setOnCheckedChangeListener { group, checkedId ->
            dareTypeId = when (checkedId) {
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnSanXiao.id -> 11
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnLiuXiao.id -> 12
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnJiuXiao.id -> 13
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtn5ma.id -> 14
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtn10ma.id -> 15
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtn20ma.id -> 16
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtn35ma.id -> 17
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnPingTeYiXiao.id -> 18
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnPingTeYiWei.id -> 19
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnWuBuZhong.id -> 20
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnQiBuZhong.id -> 21
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnSanZhongYi.id -> 22
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnErLianXiao.id -> 23
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnErLianWei.id -> 24
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnDanShuang.id -> 25
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnDaXiao.id -> 26
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnJiaYe.id -> 27
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnShuangBo.id -> 28
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnHeDanShuang.id -> 29
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnSanTou.id -> 30
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnLiuWei.id -> 31
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnSanHang.id -> 32
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnQiWei.id -> 33
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnShaYiXiao.id -> 34
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnSha5ma.id -> 35
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnShaYiTou.id -> 36
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnShaYiWei.id -> 37
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnShaYiDuan.id -> 38
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnShaYiHang.id -> 39
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnShaErWei.id -> 40
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnShaErXiao.id -> 41
                binding.subscribeRecordLayoutSelector.challengeTypeSelectorBtnShaBanBo.id -> 42
                else -> 11
            }
            fetchSubscribeRecordList()
        }

        LiveDataBus.get().with(BusKey.SUBSCRIBE_TYPE_CHANGE, Int::class.java).observe(this) {
            fetchSubscribeRecordList()
        }
    }

    override fun lazyLoad() {
        fetchSubscribeRecordList()
    }

    override fun onBack() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(subscribeViewModel.subscribeRecordListLiveData, ::handleGetSubRecordList)
        observe(subscribeViewModel.likeLiveData, ::handleSetLike)
        observe(subscribeViewModel.subscribeLiveData, ::handleUnSetSubscribe)
    }

    private fun handleGetSubRecordList(result: Resource<MutableList<FamousItemBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.subscribeRecordSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取订阅战绩信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.subscribeRecordSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                mAdapter.setList(result.data!!)
            }
        }
    }

    private fun handleSetLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                }
                val item = mAdapter.data[clickPos]
                item.like = true
                item.nicePoint += 1
                mAdapter.notifyItemChanged(clickPos)
            }
        }
    }

    private fun handleUnSetSubscribe(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("订阅失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                }
                fetchSubscribeRecordList()
            }
        }
    }

    private fun fetchSubscribeRecordList() {
        val type = (requireActivity() as FamousMySubscribeActivity).famousType
        subscribeViewModel.getSubscribeRecordList(dareTypeId, type, AppBackgroundInfo.instance.userBean!!.userId)
    }
}